<template>
  <div class="category-container">
    <div class="category-wrapper">
      <!-- 左侧分类树 -->
      <el-card class="category-tree-card">
        <template #header>
          <div class="card-header">
            <span>分类列表</span>
            <div>
              <el-button type="primary" size="small" @click="handleAddRoot">添加根分类</el-button>
            </div>
          </div>
        </template>
        <div class="tree-container" v-loading="treeLoading">
          <el-tree
            ref="treeRef"
            :data="categoryTree"
            :props="{ label: 'name', children: 'children' }"
            :expand-on-click-node="false"
            default-expand-all
            node-key="id"
            highlight-current
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <div class="node-label">
                  <el-tag v-if="data.level === 1" type="success" size="small" effect="plain">一级</el-tag>
                  <el-tag v-else-if="data.level === 2" type="warning" size="small" effect="plain">二级</el-tag>
                  <el-tag v-else-if="data.level === 3" type="danger" size="small" effect="plain">三级</el-tag>
                  <span :class="{ 'node-disabled': data.status === '0' }">{{ node.label }}</span>
                </div>
                <div class="node-operations">
                  <el-tag size="small" :type="data.status === '1' ? 'success' : 'info'">
                    {{ data.status === '1' ? '启用' : '禁用' }}
                  </el-tag>
                  <el-button-group>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click.stop="handleAddChild(data)"
                      :disabled="data.level >= 3"
                    >添加</el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click.stop="handleEdit(data)"
                    >编辑</el-button>
                    <el-button
                      link
                      type="primary"
                      size="small"
                      @click.stop="handleChangeStatus(data)"
                    >{{ data.status === '1' ? '禁用' : '启用' }}</el-button>
                    <el-button
                      link
                      type="danger"
                      size="small"
                      @click.stop="handleDelete(data)"
                      :disabled="data.children && data.children.length > 0"
                    >删除</el-button>
                  </el-button-group>
                </div>
              </div>
            </template>
          </el-tree>
          <div v-if="categoryTree.length === 0" class="no-data">
            <el-empty description="暂无分类数据" />
          </div>
        </div>
      </el-card>

      <!-- 右侧详情 -->
      <el-card class="category-detail-card" v-if="currentCategory.id">
        <template #header>
          <div class="card-header">
            <span>分类详情</span>
          </div>
        </template>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="分类名称">{{ currentCategory.name }}</el-descriptions-item>
          <el-descriptions-item label="分类状态">
            <el-tag :type="currentCategory.status === '1' ? 'success' : 'info'">
              {{ currentCategory.status === '1' ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="排序">{{ currentCategory.sort }}</el-descriptions-item>
          <el-descriptions-item label="父级分类">{{ currentCategory.parentName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="分类描述">{{ currentCategory.description || '无' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentCategory.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentCategory.updateTime }}</el-descriptions-item>
        </el-descriptions>
        <div class="detail-operations">
          <el-button-group>
            <el-button type="primary" @click="handleEdit(currentCategory)">编辑</el-button>
            <el-button 
              type="primary" 
              @click="handleChangeStatus(currentCategory)"
            >{{ currentCategory.status === '1' ? '禁用' : '启用' }}</el-button>
            <el-button
              type="danger"
              @click="handleDelete(currentCategory)"
              :disabled="currentCategory.children && currentCategory.children.length > 0"
            >删除</el-button>
          </el-button-group>
        </div>
      </el-card>
      <el-empty v-else description="请选择分类查看详情" class="empty-detail" />
    </div>

    <!-- 分类表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      destroy-on-close
      @closed="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId" v-if="dialogType !== 'editRoot'">
          <el-cascader
            v-model="formData.parentId"
            :options="categoryOptions"
            :props="{
              checkStrictly: true,
              label: 'name',
              value: 'id',
              emitPath: false,
              expandTrigger: 'hover'
            }"
            clearable
            :disabled="dialogType === 'addChild'"
            placeholder="请选择父级分类"
          />
        </el-form-item>
        <el-form-item label="分类状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="分类描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入分类描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { categoryApi } from '@/api/product'

// 分类树数据
const categoryTree = ref([])
const treeLoading = ref(false)
const treeRef = ref(null)

// 当前选中的分类
const currentCategory = ref({})

// 分类选项（用于级联选择器）
const categoryOptions = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const dialogType = ref('') // addRoot, addChild, edit, editRoot
const formRef = ref(null)
const submitLoading = ref(false)
const formData = reactive({
  name: '',
  parentId: undefined,
  status: '1',
  sort: 0,
  description: ''
})

// 表单校验规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  parentId: [
    { required: true, message: '请选择父级分类', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序值', trigger: 'blur' }
  ]
}

// 获取分类树
const getCategoryTree = async () => {
  treeLoading.value = true
  try {
    const res = await categoryApi.getList()
    console.log('分类接口返回数据:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的多种数据结构
      let categoryData = null
      
      // 处理直接返回数组的情况
      if (Array.isArray(res.data)) {
        categoryData = res.data
      } 
      // 处理 {rows: [...], total: ...} 结构
      else if (res.data && Array.isArray(res.data.rows)) {
        categoryData = res.data.rows
      }
      // 处理嵌套结构 res.data.data 的情况
      else if (res.data && res.data.data) {
        // 处理新的嵌套结构：{code, msg, data: [...]}}
        if (res.data.code && res.data.msg && Array.isArray(res.data.data)) {
          categoryData = res.data.data
        }
        else if (Array.isArray(res.data.data)) {
          categoryData = res.data.data
        } 
        // 处理 res.data.data.rows 的情况
        else if (res.data.data.rows && Array.isArray(res.data.data.rows)) {
          categoryData = res.data.data.rows
        }
      }
      // 处理新的嵌套结构：{code, msg, data: {code, msg, data: [...]}}
      else if (res.data && res.data.code && res.data.data && res.data.data.data) {
        if (Array.isArray(res.data.data.data)) {
          categoryData = res.data.data.data
        }
      }
      
      if (categoryData) {
        categoryTree.value = categoryData
        // 同时更新级联选择器的选项
        categoryOptions.value = JSON.parse(JSON.stringify(categoryData))
        console.log('处理后的分类数据:', categoryData)
      } else {
        console.warn('分类数据结构与预期不符，请检查API返回格式', res.data)
        ElMessage.warning('获取分类数据格式异常，请联系管理员')
        categoryTree.value = []
        categoryOptions.value = []
      }
    } else {
      ElMessage.error(res.msg || '获取分类列表失败')
      categoryTree.value = []
      categoryOptions.value = []
    }
    return Promise.resolve() // 确保返回Promise
  } catch (error) {
    console.error('获取分类列表出错', error)
    ElMessage.error('获取分类列表出错: ' + (error.message || '未知错误'))
    categoryTree.value = []
    categoryOptions.value = []
    return Promise.reject(error) // 出错时返回rejected Promise
  } finally {
    treeLoading.value = false
  }
}

// 点击节点事件
const handleNodeClick = async (data) => {
  currentCategory.value = data
  // 如果当前分类有父级ID，获取父级分类的名称
  if (data.parentId && data.parentId !== 0) {
    try {
      const res = await categoryApi.getDetail(data.parentId)
      if (res.code === 200 || res.code === '200') {
        let parentData = null
        if (res.data && typeof res.data === 'object') {
          if (res.data.code && res.data.msg && res.data.data) {
            parentData = res.data.data
          } else {
            parentData = res.data
          }
        }
        if (parentData) {
          currentCategory.value.parentName = parentData.name
        }
      }
    } catch (error) {
      console.error('获取父级分类详情出错', error)
    }
  } else {
    currentCategory.value.parentName = '无'
  }
}

// 添加根分类
const handleAddRoot = () => {
  resetForm()
  dialogType.value = 'addRoot'
  dialogTitle.value = '添加根分类'
  formData.parentId = 0 // 根分类的父ID为0
  dialogVisible.value = true
}

// 添加子分类
const handleAddChild = (data) => {
  resetForm()
  dialogType.value = 'addChild'
  dialogTitle.value = '添加子分类'
  formData.parentId = data.id
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = async (data) => {
  resetForm()
  try {
    const res = await categoryApi.getDetail(data.id)
    console.log('分类详情接口返回:', res) // 调试日志
    
    if (res.code === 200 || res.code === '200') {
      // 处理可能的嵌套数据结构
      let detailData = null
      
      // 直接是对象的情况
      if (res.data && typeof res.data === 'object' && !Array.isArray(res.data)) {
        // 检查新的嵌套结构：{code, msg, data: {id, parentId, ...}}
        if (res.data.code && res.data.msg && res.data.data && typeof res.data.data === 'object') {
          detailData = res.data.data
        } else {
          detailData = res.data
        }
      }
      // 嵌套一层的情况：res.data.data
      else if (res.data && res.data.data && typeof res.data.data === 'object' && !Array.isArray(res.data.data)) {
        detailData = res.data.data
      }
      // 新的嵌套结构：{code, msg, data: {code, msg, data: {...}}}
      else if (res.data && res.data.code && res.data.data && res.data.data.data && typeof res.data.data.data === 'object') {
        detailData = res.data.data.data
      }
      
      if (!detailData) {
        console.warn('分类详情数据结构与预期不符', res.data)
        ElMessage.warning('获取分类详情格式异常')
        return
      }
      
      console.log('提取后的详情数据:', detailData) // 调试日志
      
      // 更新表单数据
      Object.assign(formData, detailData)
      dialogType.value = formData.parentId === 0 ? 'editRoot' : 'edit'
      dialogTitle.value = '编辑分类'
      dialogVisible.value = true
    } else {
      ElMessage.error(res.msg || '获取分类详情失败')
    }
  } catch (error) {
    console.error('获取分类详情出错', error)
    ElMessage.error('获取分类详情出错: ' + (error.message || '未知错误'))
  }
}

// 更改分类状态
const handleChangeStatus = (data) => {
  const newStatus = data.status === '1' ? '0' : '1'
  const statusText = newStatus === '1' ? '启用' : '禁用'
  
  ElMessageBox.confirm(`确定要${statusText}分类"${data.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await categoryApi.updateStatus({
        id: data.id,
        status: newStatus
      })
      console.log('更新状态返回:', res) // 调试日志
      
      if (res.code === 200 || res.code === '200') {
        // 处理可能的嵌套响应
        let updateSuccess = true;
        
        // 检查是否有嵌套的响应结构
        if (res.data && res.data.code && res.data.code !== 200 && res.data.code !== '200') {
          ElMessage.error(res.data.msg || `${statusText}失败`)
          updateSuccess = false;
        }
        
        if (updateSuccess) {
          ElMessage.success(`${statusText}成功`)
          getCategoryTree()
          if (currentCategory.value.id === data.id) {
            currentCategory.value.status = newStatus
          }
        }
      } else {
        ElMessage.error(res.msg || `${statusText}失败`)
      }
    } catch (error) {
      console.error(`${statusText}分类出错`, error)
      ElMessage.error(`${statusText}分类出错: ` + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// 删除分类
const handleDelete = (data) => {
  if (data.children && data.children.length > 0) {
    ElMessage.warning('该分类下还有子分类，不能删除')
    return
  }
  
  ElMessageBox.confirm(`确定要删除分类"${data.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await categoryApi.deleteCategory(data.id)
      console.log('删除分类返回:', res) // 调试日志
      
      if (res.code === 200 || res.code === '200') {
        // 处理可能的嵌套响应
        let deleteSuccess = true;
        
        // 检查是否有嵌套的响应结构
        if (res.data && res.data.code && res.data.code !== 200 && res.data.code !== '200') {
          ElMessage.error(res.data.msg || '删除失败')
          deleteSuccess = false;
        }
        
        if (deleteSuccess) {
          ElMessage.success('删除成功')
          getCategoryTree()
          if (currentCategory.value.id === data.id) {
            currentCategory.value = {}
          }
        }
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除分类出错', error)
      ElMessage.error('删除分类出错: ' + (error.message || '未知错误'))
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      submitLoading.value = true
      try {
        const api = formData.id ? categoryApi.updateCategory : categoryApi.addCategory
        const submitData = { ...formData }
        
        console.log('提交分类表单数据:', submitData) // 调试日志
        const res = await api(submitData)
        console.log('提交分类表单返回:', res) // 调试日志
        
        if (res.code === 200 || res.code === '200') {
          ElMessage.success(formData.id ? '修改成功' : '新增成功')
          dialogVisible.value = false
          getCategoryTree()
          // 如果是编辑当前选中的分类，需要更新详情
          if (formData.id && currentCategory.value.id === formData.id) {
            try {
              const detailRes = await categoryApi.getDetail(formData.id)
              console.log('更新后的分类详情:', detailRes) // 调试日志
              
              if (detailRes.code === 200 || detailRes.code === '200') {
                // 处理嵌套数据结构
                let updatedData = null
                
                // 直接是对象的情况
                if (detailRes.data && typeof detailRes.data === 'object' && !Array.isArray(detailRes.data)) {
                  // 检查新的嵌套结构：{code, msg, data: {id, parentId, ...}}
                  if (detailRes.data.code && detailRes.data.msg && detailRes.data.data && typeof detailRes.data.data === 'object') {
                    updatedData = detailRes.data.data
                  } else {
                    updatedData = detailRes.data
                  }
                }
                // 嵌套一层的情况：res.data.data
                else if (detailRes.data && detailRes.data.data && typeof detailRes.data.data === 'object' && !Array.isArray(detailRes.data.data)) {
                  updatedData = detailRes.data.data
                }
                // 新的嵌套结构：{code, msg, data: {code, msg, data: {...}}}
                else if (detailRes.data && detailRes.data.code && detailRes.data.data && detailRes.data.data.data && typeof detailRes.data.data.data === 'object') {
                  updatedData = detailRes.data.data.data
                }
                
                if (updatedData) {
                  currentCategory.value = updatedData
                } else {
                  console.warn('更新后的分类详情数据结构与预期不符', detailRes.data)
                }
              }
            } catch (detailError) {
              console.error('获取更新后的分类详情出错', detailError)
            }
          }
        } else {
          ElMessage.error(res.msg || (formData.id ? '修改失败' : '新增失败'))
        }
      } catch (error) {
        console.error(formData.id ? '修改分类出错' : '新增分类出错', error)
        ElMessage.error((formData.id ? '修改分类出错' : '新增分类出错') + ': ' + (error.message || '未知错误'))
      } finally {
        submitLoading.value = false
      }
    } else {
      console.log('表单校验失败', fields)
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: undefined,
    name: '',
    parentId: undefined,
    status: '1',
    sort: 0,
    description: ''
  })
}

// 初始化
onMounted(() => {
  console.log('分类管理组件初始化')
  
  // 检查接口是否可用
  try {
    getCategoryTree()
  } catch (error) {
    console.error('初始化分类树失败:', error)
    ElMessage.error('加载分类数据失败，请稍后刷新页面')
  }
  
  // 监听窗口大小变化，调整树的高度
  const handleResize = () => {
    // 这里可以添加调整树高度的逻辑
  }
  window.addEventListener('resize', handleResize)
  handleResize()
})
</script>

<style scoped>
.category-container {
  padding: 20px;
}

.category-wrapper {
  display: flex;
  gap: 20px;
}

.category-tree-card {
  width: 500px;
  flex-shrink: 0;
}

.category-detail-card {
  flex: 1;
}

.empty-detail {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-container {
  min-height: 400px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 8px;
}

.node-label {
  display: flex;
  align-items: center;
  gap: 8px;
}

.node-operations {
  display: flex;
  gap: 8px;
  align-items: center;
}

.node-disabled {
  color: #909399;
  text-decoration: line-through;
}

.detail-operations {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.no-data {
  padding: 40px 0;
}
</style> 